extern crate gateway_service;

use std::collections::HashMap;

use bencher::{benchmark_group, benchmark_main, Bencher};
use gateway_service::{Service, ServiceBook};
use rand::Rng;

fn service_choice_bench(bencher: &mut Bencher) {
    let mut servicebook = ServiceBook::new();
    // 200个服务，每个服务10个负载
    for i in 0..2000 {
        servicebook
            .join_service(
                (i % 200).to_string(),
                Service {
                    host: "127.0.0.1".into(),
                    port: i,
                    name: "ZHRD".into(),
                },
            )
            .unwrap();
    }
    let mut rng = rand::thread_rng();
    bencher.iter(|| {
        servicebook
            .choose_service(rng.gen_range(1..200).to_string())
            .unwrap()
            .get_url()
    });
}

fn service_get_bench(bencher: &mut Bencher) {
    let mut servicebook = ServiceBook::new();
    // 200个服务，每个服务10个负载
    for i in 0..2000 {
        servicebook
            .join_service(
                (i % 200).to_string(),
                Service {
                    host: "127.0.0.1".into(),
                    port: i,
                    name: "ZHRD".into(),
                },
            )
            .unwrap();
    }
    let mut rng = rand::thread_rng();
    bencher.iter(|| {
        servicebook
            .get_service(rng.gen_range(1..200).to_string())
            .unwrap()
    });
}

fn hashmap_get_bench(bencher: &mut Bencher) {
    // 200个节点的hashmap数据获取测试
    let mut _map = HashMap::new();
    for i in 0..2000 {
        let service = Service {
            host: "127.0.0.1".into(),
            port: i,
            name: "ZHRD".into(),
        };
        match _map.get_mut((i % 200).to_string().as_str()) {
            None => {
                _map.insert((i % 200).to_string(), vec![service]);
            }
            Some(senders) => {
                senders.insert(0, service);
            }
        };
    }
    let mut rng = rand::thread_rng();
    bencher.iter(
        || if _map.get_mut(rng.gen_range(0..200).to_string().as_str()).is_some() {},
    );
}

fn rang_bench(bencher: &mut Bencher) {
    let mut rng = rand::thread_rng();
    bencher.iter(|| rng.gen_range(1..200).to_string());
}

benchmark_group!(
    benches,
    service_choice_bench,
    rang_bench,
    service_get_bench,
    hashmap_get_bench
);
benchmark_main!(benches);
